package com.youkeyi.ddy.cloud.common.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * RepeatSubmitCheckHttpServletRequestWrapperFilter
 *
 * @Author liuxiawang
 * @Date 4/2/22 5:23 PM
 * @Location shenzhen.china
 */
@WebFilter(filterName = "repeatSubmitCheckhttpServletRequestWrapperFilter", urlPatterns = {"/system/**", "/supply/chain/web/**", "/supply/chain/applet/**"})
@Component
public class RepeatSubmitCheckHttpServletRequestWrapperFilter implements Filter {

    @Value("${youkeyi.filter.repeatsubmit.url.exclude:}")
    private String excludeUrlPatterns;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            boolean isExcludePath = false;
            String requestURI = httpRequest.getRequestURI();
            if (StringUtils.isNotBlank(excludeUrlPatterns)) {
                String[] split = excludeUrlPatterns.split(",");
                if (split.length > 0) {
                    for (String url : split) {
                        Pattern pattern = Pattern.compile(url);
                        Matcher matcher = pattern.matcher(requestURI);
                        if (matcher.find()) {
                            isExcludePath = true;
                            break;
                        }
                    }
                }
            }

            if (!isExcludePath) {
                // 遇到post方法才对request进行包装
                String methodType = httpRequest.getMethod();
                if ("POST".equals(methodType) || "PATCH".equals(methodType)) {
                    try {
                        requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (null == requestWrapper) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy() {

    }
}

